﻿using Microsoft.AspNetCore.Mvc;
using PetaPoco;
using Qy.Common;
using Qy.Models;
using Qy.Service;
using Qy.Web.Authorize;
using System.IO;
using System.Threading.Tasks;

namespace Qy.Web.Api
{
    [Route("Api/[controller]/[action]")]
    [Verify]
    public class AttmentController : Base
    {
        private readonly LoginUtil _LoginUtil;
        private readonly AttmentService _attment;
        public AttmentController(LoginUtil LoginUtil,AttmentService attmentService)
        {
            _LoginUtil = LoginUtil;
            _attment = attmentService;
        }

        [HttpGet]
        [ActionPermissionFilter(Permission = PermissionKeys.Attment_Index)]
        public async Task<IActionResult> IndexAsync(int page = 1, int limit = 15)
        {
            UserInfo adminUser = await _LoginUtil.UserInfoAsync();
            int adminUid = adminUser.Gid != 1 ? adminUser.UserId : 0;//超级管理员显示全部数据
            Page<ViewAttment> list = await _attment.GetPageListAsync(page, limit, adminUid);
            return Json(new {status=1, data = list.Items, count = list.TotalItems });
        }

        [HttpDelete]
        [ActionPermissionFilter(Permission = PermissionKeys.Attment_Delete)]
        [Log(Name = "删除上传文件")]
        public async Task<IActionResult> DeleteAsync(int id)
        {
            Attment attment = await _attment.GetAsync(id);
            string filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot") + "\\" + attment.Url;
            if (FileUtility.FileExists(filePath))
            {
                FileUtility.FileDel(filePath);
            }
            if (await _attment.DeleteByPriKeyAsync(id) > 0)
            {
                return Json(new { status = 1, msg = "删除上传文件 id:" + id });
            }
            else
                return Json(new { status = 0, msg = "删除上传文件 id:" + id });
        }
    }
}
